package com.cincc.cincc_pbx.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.cincc.cincc_pbx.R;
import com.cincc.cincc_pbx.common.MyUtils;
import com.cincc.cincc_pbx.common.OkHttpUtils;
import com.cincc.cincc_pbx.common.SharePreferenceUtil;
import com.cincc.cincc_pbx.constant.AttrsConstant;
import com.cincc.cincc_pbx.constant.CallConstant;
import com.gyf.immersionbar.ImmersionBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import okhttp3.Call;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private static final String TAG = "LoginActivity";
    EditText vccIdEdit;
    EditText usernameEdit;
    EditText passwordEdit;
    EditText codeEdit;
    ImageView codeImage;

    View extensionLine;
    LinearLayout extensionLinearlayout;
    CheckBox extensionCheck;
    EditText extensionEdit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        initView();
    }

    private void initView() {
        vccIdEdit = findViewById(R.id.edit_vccId);
        usernameEdit = findViewById(R.id.edit_username);
        passwordEdit = findViewById(R.id.edit_password);
        codeEdit = findViewById(R.id.edit_code);
        codeImage = findViewById(R.id.code_img);

        extensionLine = findViewById(R.id.extension_line);
        extensionLinearlayout = findViewById(R.id.extension_ll);
        extensionCheck = findViewById(R.id.extension_check);
        extensionEdit = findViewById(R.id.edit_extension);


        RelativeLayout imageRelayout = findViewById(R.id.login_relayout);

        codeImage.setOnClickListener(this);
        imageRelayout.setOnClickListener(this);
        extensionCheck.setOnCheckedChangeListener(this);

        loadData();
        refreshCode();
    }

    private void loadData() {
        String vccid = (String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.VCCID, "");
        String userName = (String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.USERNAME, "");
        String password = (String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.PASSWORD, "");
        vccIdEdit.setText(vccid);
        usernameEdit.setText(userName);
        passwordEdit.setText(password);
    }

    private void saveData() {
        String vccid = vccIdEdit.getText().toString();
        String userName = usernameEdit.getText().toString();
        String password = passwordEdit.getText().toString();

        SharePreferenceUtil.getInstance().setValue(AttrsConstant.VCCID, vccid);
        SharePreferenceUtil.getInstance().setValue(AttrsConstant.USERNAME, userName);
        SharePreferenceUtil.getInstance().setValue(AttrsConstant.PASSWORD, password);
    }

    String codeVerify = "";

    private void refreshCode() {
        String path = CallConstant.REQUEST_VERIFY_CODE_URL + System.currentTimeMillis();
        new Thread(() -> {
            try {
                Map<String, Bitmap> image = MyUtils.getImage(path);
                if (image != null) {
                    codeVerify = (String) image.keySet().toArray()[0];
                    Log.e(TAG, "refreshCode: verifyKey = " + codeVerify);
                    runOnUiThread(() -> codeImage.setImageBitmap(image.get(codeVerify)));
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(LoginActivity.this, "获取验证码失败", Toast.LENGTH_SHORT).show();
                    });
                }
            } catch (Exception e) {
                runOnUiThread(() -> {
                    Toast.makeText(LoginActivity.this, "获取验证码失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    private void login() {
        String userName = usernameEdit.getText().toString();
        String password = passwordEdit.getText().toString();
        String vccId = vccIdEdit.getText().toString();
        String code = codeEdit.getText().toString();
        String extension = extensionEdit.getText().toString();
        CallConstant.loginModel.setExtension(extension);
        String passwordEncode = MyUtils.encodePassword(password);
        Log.e(TAG, "login: passwordEncode = " + passwordEncode);

        OkHttpUtils.builder().url(CallConstant.REQUEST_LOGIN_URL).
                addParam("username", userName).addParam("password", passwordEncode).
                addParam("verifyCode", code).addParam("verifyKey", codeVerify).
                addParam("tenantId", vccId).addParam("systemId", "101").post(true).async(new OkHttpUtils.ICallBack() {
                    @Override
                    public void onSuccessful(Call call, String data) {
                        Log.e(TAG, "login onSuccessful: " + data);
                        try {
                            JSONObject j = new JSONObject(data);
                            String code = j.getString("rtnCode");
                            String msg = j.getString("rtnMsg");
                            if (code.equals("0000")) {
                                JSONObject jsonObject = j.getJSONObject("data");
                                String accessToken = jsonObject.getString("accessToken");
                                String refreshToken = jsonObject.getString("refreshToken");
                                CallConstant.loginModel.setData(userName, vccId, accessToken, refreshToken);
                                runOnUiThread(() -> startMain());
                            } else {
                                //验证码输入错误，就会失效，需要重新刷新验证码
                                if (code.equals("401")) {
                                    refreshCode();
                                }
                                runOnUiThread(() -> {
                                    Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call call, String errorMsg) {
                        Log.e(TAG, "login onFailure: " + errorMsg);
                        runOnUiThread(() -> Toast.makeText(LoginActivity.this, errorMsg, Toast.LENGTH_SHORT).show());
                    }
                });
    }

    private void startMain() {
        saveData();
        Intent i = new Intent(this, MainActivity.class);
        startActivity(i);
        finish();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.code_img) {
            refreshCode();
        } else if (v.getId() == R.id.login_relayout) {
            login();
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        extensionLine.setVisibility(isChecked ? View.VISIBLE : View.GONE);
        extensionLinearlayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
        if (!isChecked) {
            extensionEdit.setText("");
        }
    }
}
